package com.briup.day31.guitu;
/**
 * 龟兔赛跑（版本二：真实竞赛）
 * */
public class TortoiseAndRabbitRace2_1 {
	
	static class Tortoise extends Thread{  
		long score; 
		
		public long getScore() {
			return score;
		}

		public Tortoise(String name) {
			super(name);
		}
		
		@Override
		public void run() {
			int sum = 0;
			long t1 = System.currentTimeMillis();
			while (sum < 100) {
				int meter = (int)(Math.random() * 3 + 2);
				sum += meter;
				System.out.println(getName()+"本次跑了"+meter
						+"米,当前一共跑了"+ sum +"米。");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
				
				}
				
			}
			long t2 = System.currentTimeMillis();
			System.out.println(getName()+"耗时"+(t2 - t1)+"毫秒。");
			score = t2 - t1;

		}
		
	}
	
	static class Rabbit extends Thread{  
		public Rabbit(String name) {
			super(name);
		}
		long score; 
		public long getScore() {
			return score;
		}
		@Override
		public void run() {
			int sum = 0;
			long t1 = System.currentTimeMillis();
			while (sum < 100) {
				//先决定兔子本次是否想睡觉
				int random = (int)(Math.random() * 100 + 1);
				if (random <= 30) {
					System.out.println("兔兔睡觉");
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}else {
					int meter = (int)(Math.random() * 3 + 7);
					sum += meter;
					System.out.println(getName()+"本次跑了"+meter
							+"米,当前一共跑了"+ sum +"米。");
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
					
					}
				}
				
			}
			long t2 = System.currentTimeMillis();
			System.out.println(getName()+"耗时"+(t2 - t1)+"毫秒。");
			score = t2 - t1;

		}
		
	}
	
	
	public static void main(String[] args) {
		
		Rabbit t1 = new Rabbit("兔兔");
		Tortoise t2 = new Tortoise("乌龟");
		
		t1.start();
		t2.start();
		
		try {
			t1.join();  //main排在a1之后
			t2.join();  //main排在a2之后
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//t1.stop();
		
		System.out.println(t1.getScore() < t2.getScore() ? t1.getName()+"获胜!"
				: t1.getScore() > t2.getScore() ? t2.getName() + "获胜!" : "平局!");
		

	}

}
